import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { useStorage } from 'vue3-storage'
import { ACCESS_TOKEN } from '@/utils/constant'

const storage = useStorage()

const Request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_PATH,
  timeout: 6 * 1000,
  withCredentials: true
})

Request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = storage.getStorageSync(ACCESS_TOKEN)
    /*
     * 如果 token 存在
     * 让每个请求携带自定义 token 请根据实际情况自行修改
     */
    if (token && config.headers && !config.headers.Authorization) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

Request.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.status === 200) {
      return Promise.resolve(response.data.data || response.data)
    } else {
      return Promise.reject(response)
    }
  },
  (error) => {
    return Promise.reject((error.response || {}).data || {})
  }
)

export {
  Request
}
